
var logindata = {
	"host":{"type":"text","title":"主机","value":"127.0.0.1"},
	"port":{"type":"number","title":"端口","value":"8093"},
	"username":{"type":"text","title":"用户名","value":"root"},
	"password":{"type":"password","title":"密码","value":"root"}
};
var host;
var port;
var Adata = new Object();
Adata.username = "";
Adata.hash = "";//通信验证码
var messages = [];// Array(N);
var readyState=["连接尚未建立","连接正常","连接正在关闭","连接已经关闭"];
var conrr = {"nginx":"nginx","php":"php","mysql":"mysql","memcache":"memcache","all":"所有"};
var conbtn = {"start":"启动","stop":"停止","restart":"重启"};
var conbtns = {"start":"一键启动","stop":"一键停止","restart":"一键重启"};
//--全局信号
var Asignal = {
	'4':{"color":"#00ff40","msg":"运行"},
	'2':{"color":"red","msg":"停止"}
};
var Aopt_OnOff = {"On":"打开","Off":"关闭"};
var Aopt_charset = {"utf-8":"utf-8","gbk":"gbk","gb2312":"gb2312"};
var Asetopt = {
	"anmp":{
		"nginx":{
			"log_time":{name:"日志分割频率",type:"number",remark:"次每周期"},
			"log_cycle":{name:"日志分割周期",type:"radio",opt:{"1":"每天","2":"每周","3":"每月"}},
			"auto_del_log":{name:"自动删除日志",type:"number",remark:"周期前"}
		},
		"php":{
			"childs":	{name:"CGI进程数",type:"number"},
			"version":	{name:"版本",type:"select",opt:{"5.2.17":"5.2.17","5.3.6":"5.3.6","5.3.8":"5.3.8"}}
		},"mysql":{
			"ini":		{name:"配置文件",type:"text"},
			"version":	{name:"版本",type:"select",opt:{"5.1":"5.1","7.1":"7.1"}}
		}
	},
/*	"user":{
		"username":{type:"text"},
		"password":{type:"password"}
	},*/
	"php":{
		"PHP":{
			"allow_url_fopen":			{name:"允许打开远程文件",type:"radio",opt:Aopt_OnOff},
			"allow_url_include":		{name:"允许打开包含文件",type:"radio",opt:Aopt_OnOff},
			"default_charset":			{name:"默认编码",type:"select",opt:Aopt_charset},
			"default_socket_timeout":	{name:"socket通信超时",type:"number","remark":"秒"},
			"file_uploads":				{name:"上传功能",type:"radio",opt:Aopt_OnOff},
			"memory_limit":				{name:"最大执行内存",type:"text"},
			"post_max_size":			{name:"POST最大尺寸",type:"text"},
			"upload_max_filesize":		{name:"上传最大尺寸",type:"text"}
		},"Date":{
			"date.timezone":			{name:"默认时区",type:"text"}
		}
	},
	"mysql":{
		"mysqld":{
			"basedir":					{name:"程序目录",type:"text"},
			"datadir":					{name:"数据目录",type:"text"},
			"port":						{name:"端口",type:"number"},
			"key_buffer":				{name:"KEY缓存",type:"text"},
			"max_allowed_packet":		{name:"最大允许包",type:"text"},
			"table_cache":				{name:"表缓存数",type:"number"},
			"thread_cache":				{name:"线程缓存数",type:"number"},
			"join_buffer_size":			{name:"join缓存大小",type:"text"},
			"sort_buffer":				{name:"sort缓存",type:"text"},
			"record_buffer":			{name:"record缓存",type:"text"},
			"max_connections":			{name:"最大连接数",type:"number"},
			"wait_timeout":				{name:"等待超时",type:"number","remark":"秒"},
			"interactive_timeout":		{name:"互动超时",type:"number","remark":"秒"},
			"max_connect_errors":		{name:"最大连接错误",type:"number"},
			"long_query_time":			{name:"long_query_time",type:"number"},
			"max_heap_table_size":		{name:"最大堆表的大小",type:"text"},
			"tmp_table_size":			{name:"临时表大小",type:"text"},
			"thread_concurrency":		{name:"线程并发",type:"number"},
			"myisam_sort_buffer_size":	{name:"myisam sort缓存",type:"text"}
		}
	}
};
var Alink = {
	'0':{"name":"web控制台","url":":93","target":"_blank","type":1},
	'1':{"name":"phpmyadmin","url":":85","target":"_blank","type":1},
	'2':{"name":"Anmp官网","url":"www.abans.cn","target":"_blank","type":2},
	'3':{"name":"Anmp博客","url":"hi.baidu.com/igarden","target":"_blank","type":2}
};
var userdata;
var Asetdata;
var _in = 0, _out = 0;

var Anmp=Object();
Anmp = function(obj){return Anmp.anew(obj);}
Anmp.anew = function(obj){this.obj=obj;	return this;}
//--登入主机
Anmp.login = function(){
	var html="";
	for (var x in logindata) {
		html += Ahtml.tag("dt",{},logindata[x].title+":")+Ahtml.tag("dd",{},Ahtml.tag("input",{"type":logindata[x].type,"class":x,"value":logindata[x].value}));
	};
	html = Ahtml.tag("dl",{"class":"-dl"},html);
	html += Ahtml.tag("input",{"type":"submit","value":"登入"});
	html += "<p class='-left'>登入日志：</p>"+Ahtml.tag("div",{"id":"log","class":"_login_log"});
	html = Ahtml.tag("form",{onsubmit:"Anmp.login_on();return false;"},html);
	this.win_show("Anmp 控制台登入",html,{width:"240px",height:"360px"});
	jQuery("#ajax_anmp .host").focus();
}
Anmp.login_on = function(){
	userdata = Object();
	for (var x in logindata) {
		userdata[x] = jQuery("#ajax_anmp ."+x).val();
	};
	if(userdata.host==""){Acan.alert("请输入主机IP或者域名",1000);jQuery("#ajax_anmp .host").focus();return;}
	if(userdata.port==""){Acan.alert("请输入通信端口",1000);jQuery("#ajax_anmp .port").focus();return;}
	if(userdata.username==""){Acan.alert("请输入用户名",1000);jQuery("#ajax_anmp .username").focus();return;}
	if(userdata.password==""){Acan.alert("请输入密码",1000);jQuery("#ajax_anmp .password").focus();return;}
	this.opensocket(userdata);
}
Anmp.login_send = function(){
	this.log("开始登入...");
	Adata.app = "anmp";
	Adata.mod = "login";
	Adata.username = userdata.username;
	Adata.data = userdata.password;
	this.send(Adata);
}
Anmp.login_call = function(obj){
	if(obj.hash.length==40){
		//--登入成功
		Acan.alert(obj.data,1000);
		Adata.hash = obj.hash;
	}else if(obj.hash==3){
		//--验证失败
		Acan.alert(obj.data,1000);
		Anmp.logout();
		return;
	}else{
		//--登入失败
		Acan.alert(obj.data,1000);
		this.closesocket();
		jQuery("#ajax_anmp ."+obj.hash).focus();
		return;
	}
	Anmp.ready();
	jQuery("._hostinfo").html("当前主机:"+host+":"+port+" 开始运行:"+obj.time+" <br>登入用户:"+userdata.username+Ahtml.tag("button",{onclick:"Anmp.logout()","class":"_logout"},"退出"));
	delete obj.time;
	Acan.close('ajax_anmp');
	Anmp.check_status("all");
}
Anmp.logout = function(){
	jQuery(".-body").html("");
	this.closesocket();
	this.login();
}
Anmp.ready = function(){
	var html='<h3 class="-center">Anmp web控制台</h3>'
			+'<p class="_hostinfo"></p>'
			+'<div id="setting" class="setting"></div>'
			+'<dl id="control" class="-dl control"></dl>'
			+'<div id="link" class="link"></div>'
			+'<div id="log" class="log"></div><div id="out"></div>'
			+'<div class="status">连接状态:<span id="status_conn"/></span>检测状态:<span id="status_check"/></span></div>'
			+'<div class="system"><span>CPU</span><div class="_cpu"><span></span><div class="_cpua"></div></div><span>内存</span><div class="_img"><span></span><div class="_avail"></div></div><span class="_text"></span></div>';
	jQuery(".-body").html(html);
	//--设置
	var html="设置:";
	for(x in Asetopt){
		html += Ahtml.tag("button",{onclick:"Anmp.setting('"+x+"')"},x);
	}
	jQuery("#setting").html(html);
	//--控制台
	var html="";
	for(x in conrr){
		html += Ahtml.tag("dt",{},conrr[x])+Ahtml.tag("dd",{},this.con_btn(x));
	}
	jQuery("#control").html(html);
	//--快捷链接
	html="<b>快捷链接</b>";
	var href;
	for (x in Alink) {
		if(Alink[x].type==1){
			href = "http://"+host+Alink[x].url;
		}else{
			href = "http://"+Alink[x].url;
		}
		html += Ahtml.tag("p",{},Ahtml.tag("a",{"href":href,"target":Alink[x].target},Alink[x].name));
	};
	jQuery("#link").html(html);
}
Anmp.con_btn = function(act){
	var html="";
	var cons;
	if(act=="all"){
		cons = conbtns;
	}else{
		cons = conbtn;
		html += Ahtml.tag("span",{"class":"_"+act},"停止")+" ";
	}
	for(x in cons){
		html += Ahtml.tag("button",{onclick:"Anmp.control('"+x+"','"+act+"')"},cons[x])+" ";
	}
	return html;
}
Anmp.control = function(con,act){
	Adata.app = "anmp";//掉哪个应用
	Adata.mod = "control";//掉哪个模块
	Adata.act = act;//掉哪个动作
	Adata.data = con;//执行内容
	this.send(Adata);
}
Anmp.send = function(data){
	if(!this.checksocket()){return;}
	var jdata = Acan.base.obj_json(data);
	try{websocket.send(jdata);} catch(ex){this.log("发送错误"+ex);}
}
Anmp.log = function(str){
	var log = jQuery("#log");
	log.html(str+"<br>"+log.html());
}
Anmp.checksocket = function(){
	if(!websocket){
		Acan.alert("未连接到主机!请先连接",1000);
		return false;
	}
	return true;
}
Anmp.opensocket = function(obj){
	var i=0;
	this.log("开始连接");
	if(obj.host){
		host = obj.host;
		port = obj.port;
		whost = "ws://"+host+":"+port;
	}else{
		var whost = "ws://127.0.0.1:8000/";
	}
	try{
		this.log("初始化连接");
		websocket = new WebSocket(whost,'anmp');
		this.log("打开连接");
		websocket.onopen = function(evt) { Anmp.onOpen(evt) };
		websocket.onclose = function(evt) { Anmp.onClose(evt) };
		websocket.onmessage = function(evt) { Anmp.onMessage(evt) };
		websocket.onerror = function(evt) { Anmp.onError(evt) };
	}catch(ex){
		this.log("连接出错"+ex);
	}
	check_id = setInterval(function() {
		if(websocket.readyState==1){
			Anmp.check_status("all");
			jQuery("#status_check").text("实时检测中");
		}
		if(websocket.readyState==3){clearInterval(check_id);jQuery("#status_check").text("暂停检测");}
		i++;
	},1000);
	status_id = setInterval(function() {
		Anmp.status(readyState[websocket.readyState]+":"+i);
		if(websocket.readyState==3){clearInterval(status_id);Anmp.status("连接失败");}
		if(i>=8){i=0;}else{i++;}
	},100);
	jQuery("#msg").focus();
}
Anmp.closesocket = function(){
	if(!this.checksocket()){return;}
	try{
		msg = "退出";
		if(websocket.readyState < 2){
			websocket.send('quit');
			websocket.close();
			websocket=null;
		}
	}catch(ex){
		msg = "退出错误"+ex;
	}
	clearInterval(check_id);
	clearInterval(status_id);
	Anmp.status("连接关闭");
	jQuery("#status_check").text("暂停检测");
	this.log(msg);
}
Anmp.onOpen = function(evt){
	this.log("握手成功");
	this.login_send();
}
Anmp.onMessage = function(evt){
	obj = Acan.base.json_obj(evt.data);
	if(obj.username != Adata.username){return;}
	if(obj.mod=="login"){
		this.login_call(obj);
	}
	if(obj.hash != Adata.hash){return;}
	if(obj.mod=="check"){
		Anmp.check_call(obj);
	}else if(obj.mod=="control"){
		this.log(obj.data);
	}else if(obj.mod=="setting"){
		Anmp.setting_call(obj);
	}
}
Anmp.onError = function(evt){
	this.log("连接出错");
}
Anmp.onClose = function(evt){
	this.log("连接关闭!");
}
Anmp.status = function(msg){
	jQuery("#status_conn").text(msg);
}
Anmp.check_status = function(act){
	Adata.app = "anmp";
	Adata.mod = "check";
	Adata.act = act;
	this.send(Adata);
}
Anmp.check_call = function(obj){
	if(obj.act=="all"){
		arr = obj.data.status;
		for(x in arr){
			this.set_status(x,arr[x]);
		}
	}else{
		this.set_status(obj.act,obj.status);
	}
	if(obj.data.memory){
		arr = obj.data.memory;
		var total = Math.round(arr.total/(1024*1024));
		jQuery(".system ._text").text("总共:"+Math.round(arr.total/(1024*1024))+"MB,可用:"+Math.round(arr.avail/(1024*1024))+"MB");
		jQuery(".system ._avail").css("width",arr.load+"%");
		jQuery(".system ._img span").text(arr.load+"%");
		jQuery(".system ._cpua").css("width",arr.cpu+"%");
		jQuery(".system ._cpu span").text(arr.cpu+"%");
	}
}
Anmp.set_status = function(act,status){
	var color,msg;
	if(status!=4){status=2;}
	var obj = jQuery(".control ._"+act);
	obj.text(Asignal[status].msg);
	obj.css("background",Asignal[status].color);
}
Anmp.setting = function(act){
	Adata.app = "anmp";
	Adata.mod = "setting";
	Adata.act = act;
	Adata.data = "getdata";
	this.send(Adata);
}

Anmp.setting_save = function(act){
	Adata.app = "anmp";
	Adata.mod = "setting";
	Adata.act = act;
	if(Acan.base.in_array(Adata.act,['anmp','php','mysql'])){
		var str = "";
		for (var x in Asetdata) {
			var ai=0,strs="";
			for (var y in Asetdata[x]) {
				if(Asetopt[act][x][y].type == "radio"){
					var getval = jQuery('#ajax_anmp [name="'+x+'-'+y+'"]:checked').val();
				}else{
					var getval = jQuery('#ajax_anmp [rel="'+x+'-'+y+'"]').val();
				}
				if(typeof(getval)!="undefined"){//存在
					Asetdata[x][y] = getval;
				}
			};
		};
		Adata.data = Asetdata;
	}
	this.send(Adata);
	return;
}
Anmp.setting_call = function(obj){
	var AsetSesult = {"1":"保存成功","2":"保存失败"};
	var html="",tmp;
	if(Acan.base.in_array(obj.act,['anmp','php','mysql'])){
		if(obj.data=="result"){
			Acan.alert(AsetSesult[obj.status],1000);
			return;
		}
		if(typeof(obj.data)=="object"){
			Asetdata = obj.data;
		}else{
			Asetdata = Acan.base.json_obj(obj.data);
		}
		for (var x in Asetdata) {
			html += Ahtml.tag("p",{},"["+x+"]设置");
			tmp = "";
			for (var y in Asetdata[x]) {
				var remark = Asetopt[obj.act][x][y].remark;if(typeof(remark)=="undefined"){remark="";}
				var inputs = "";
				switch (Asetopt[obj.act][x][y].type){
					case "select":
						inputs = Ahtml.select({"rel":x+"-"+y},Asetopt[obj.act][x][y].opt,Asetdata[x][y])+remark;
						break;
					case "radio":
						inputs = Ahtml.radio({"rel":x+"-"+y,"name":x+"-"+y},Asetopt[obj.act][x][y].opt,Asetdata[x][y])+remark;
						break;
					default:
						inputs = Ahtml.tag("input",{type:Asetopt[obj.act][x][y].type,"rel":x+"-"+y,value:Asetdata[x][y]})+remark;
						break;
				}
				tmp += Ahtml.tag("dt",{},Asetopt[obj.act][x][y].name+":")+Ahtml.tag("dd",{},inputs);
			};
			html += Ahtml.tag("dl",{"class":"-dl setting"},tmp);
		};
		html += Ahtml.tag("input",{type:"submit",value:"保存"});
	}
	html = Ahtml.tag("form",{onsubmit:"Anmp.setting_save('"+obj.act+"');return false;"},html);
	this.win_show("设置:"+obj.act,html,{width:"400px",height:"360px"});
}
Anmp.win_show = function(title,html,css){
	var obj=Object();
	obj.id='ajax_anmp';
	obj["class"]='acan_win dis_none';
	if(css){
		if(!css.height) css.height='150px';
		obj.css=css;
	}else{
		obj.css={height:'150px'};
	}
	obj._close={onclick:'Acan.close(\''+obj.id+'\')','class':'-close'};//关闭按钮
	Acan.base.win(obj,title,html);
	Acan.ajax_bg();
}

jQuery(document).ready(function(){
	if(typeof(WebSocket)!="function"){
		if(typeof(MozWebSocket) == "function"){
			//火狐6+专用
			WebSocket = MozWebSocket;
			Anmp.login();
		}else{
			Anmp.win_show("浏览器兼容性问题","你的浏览器不支持或者未打开websocket通信功能，请打开或下载支持websocket的浏览器!<hr>(本程序使用HTML5书写,为了获得最好的浏览体验)Anmp推荐使用opera/chrome浏览器,可加QQ群:49642170下载Anmp优化版opera",{width:"360px",height:"240px"});
		}
	}else{
		Anmp.login();
	}
});
window.onbeforeunload=function(){
	Anmp.closesocket();
};





function send(){
	if(!checksocket()){return;}
	var txt,msg;
	txt = jQuery("#msg");
	msg = txt.val();
	if(!msg){ Acan.alert("内容不能为空",1000); return; }
	txt.value="";
	txt.focus();
	Adata.app = "anmp";//掉哪个应用
	Adata.mod = "control";//掉哪个模块
	Adata.act = "nginx";//掉哪个动作
	Adata.data = "start";//执行内容
	var jdata = Acan.base.obj_json(Adata);
	try{ this.log("发送消息:"+jdata);websocket.send(jdata); } catch(ex){ this.log("发送错误");this.log(ex); }
}
